import React, { useState } from 'react';
import { Text, TextInput, View, TouchableOpacity } from "react-native";
import tw from "twrnc";
import Icon from 'react-native-vector-icons/AntDesign';
import { router } from 'expo-router';
import CountryFlag from 'react-native-country-flag';
import { RadioButton } from 'react-native-paper';
import * as SecureStore from 'expo-secure-store';
import { NavigationProp, useNavigation } from '@react-navigation/native';

type RootStackParamList = {
    '/(tabs)/my': { id: string };
    // 其他路由的参数类型
};


export default function PwdLogin() {
  const navigation = useNavigation<NavigationProp<RootStackParamList>>();
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [isChecked, setIsChecked] = useState(false);

  const goAreaCode = () => {
    router.push('/(auth)/area-code');
  };

  const handleCheckboxChange = () => {
    setIsChecked(!isChecked);
  };

  const handleLogin = async () => {
    if (!isChecked) {
      alert('请先同意用户协议和隐私权政策');
      return;
    }
    if (!phone || !password) {
      alert('请输入手机号和密码');
      return;
    }

    const userList = await SecureStore.getItemAsync('userList');
    const userInfo = JSON.parse(userList || '[]').find(item => item.phoneNumber === phone);

    if (userInfo) {
      // 随机token
      const token = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);

      // 登录成功后保存token
      await SecureStore.setItemAsync('phoneNumber', phone)
      SecureStore.setItemAsync('token', token).then(() => {
        // navigation.navigate('/(tabs)/my', { id: userInfo.id });
        router.push('/(tabs)')
        
      })
    } else {
      alert('用户不存在');
      router.push('/(auth)/register');
    }

  };

  return (
    <View style={tw`flex-1`}>
      <View style={tw`p-4`}>
        <Text style={tw`text-right text-slate-400`} onPress={() => { router.push('/(auth)/register') }}>注册账号</Text>
        <Text style={tw`text-lg font-bold mb-8`}>密码登录</Text>

        <View
          style={tw`flex-row items-center border-2 border-gray-300 rounded-full my-1.5 px-2`}
        >
          <CountryFlag
            isoCode="CN"
            size={30}
            style={tw`rounded-full h-5 w-5 mx-3px`}
          />
          <Text>+86</Text>
          <View style={tw`mx-3px`}>
            <Icon
              name="caretdown"
              size={10}
              color="#4F8EF7"
              onPress={goAreaCode}
            />
          </View>
          <TextInput
            style={tw`p-2 flex-1`}
            placeholder="请输入手机号"
            placeholderTextColor="#999999"
            onChangeText={text => setPhone(text)}
          />
        </View>

        <View style={tw` border-2 border-gray-300 rounded-full my-1.5 px-2`}>
          <TextInput
            style={tw`p-2`}
            placeholder="请输入密码"
            placeholderTextColor="#999999"
            secureTextEntry
            onChangeText={text => setPassword(text)}
          />
        </View>

        <View style={tw`flex-row items-center justify-between my-1.5 px-5px`}>
          <Text onPress={() => router.push("/(auth)/code-login")}>
            验证码登录
          </Text>
          <Text>忘记密码?</Text>
        </View>

        <TouchableOpacity style={tw`flex-row items-center justify-center my-5`} onPress={handleLogin}>
          <View style={tw`flex items-center justify-center bg-gray-200 rounded-full w-16 h-16`}>
            <Icon name="arrowright" size={30} color="#A7ABAA" />
          </View>
        </TouchableOpacity>
      </View>



      <View
        style={tw`flex-row items-center justify-center absolute bottom-2 left-0 right-0 mx-5`}
      >
        <RadioButton
          value={String(isChecked)}
          status={isChecked ? "checked" : "unchecked"}
          onPress={handleCheckboxChange}
          color="#26EBD7"
        />
        <Text style={tw`text-teal-300`}>《WorldTalks用户协议》</Text>
        <Text>和</Text>
        <Text style={tw`text-teal-300`}>《WorldTalks隐私权政策》</Text>
      </View>
    </View>
  );
}
